import '../lib/jquery.js'
import { $messageTip, $axios } from './util.js'

const axios = $axios();

let currentPage = 1;
let pageSize = 12;
let totalItems = 0;

getAllCategory()

setTimeout(() => {
  fetchList()
  setTimeout(() => {
    bindPageEvents()
  }, 100)
}, 200)

// 获取列表
function fetchList() {
  const sortElement = $('.sortBox .active');
  const filterElement = $('.filterBox .active');
  const saleElement = $('.saleBox .active');
  const categoryElement = $('.category .active');

  return axios.get('/goods/list', { 
    params: {
      current: currentPage,
      pagesize: pageSize,
      category: categoryElement.text(),
      search: $('.search').val(),
      filter: filterElement.attr('data-type') || '',
      sortType: sortElement.attr('data-type'),
      sortMethod: sortElement.attr('data-method'),
      saleType: saleElement.attr('data-type'),
    }
   }).then(res => {
    if (res.data) {
      const data = JSON.parse(res.data);
      if (data.code === 1) {
        let html = '';

        data.list.forEach(item => {
          html += `<li data-id="${item.goods_id}">
                    <div class="show">
                      <img src="${item.img_big_logo}">
                      ${item.is_hot ? '<span class="hot">热销</span>' : ''}
                      ${item.is_sale ? '<span>折扣</span>' : ''}
                    </div>
                    <div class="info">
                      <p class="title">${item.title}</p>
                      <p class="price">
                        <span class="curr">¥ ${item.current_price}</span>
                        <span class="old">¥ ${item.price}</span>
                      </p>
                    </div>
                  </li>`;
        });

        $('.list').html(html);
        totalItems = data.total;
        $('.total').text(`${currentPage} / ${totalItems}`);
      } else {
        $messageTip(data.message);
      }
    }
  })
}

// 分类
function getAllCategory() {
  axios.get('/goods/category').then(response => {
    if (response.data) {
      const responseData = JSON.parse(response.data);
      if (responseData.code === 1) {
        let html = '';
        responseData.list.forEach((item, index) => {
          html += `<li class="${index === 0 ? 'active' : ''}">${item}</li>`;
        });
        $('.category').html(html);
      }
    }
  });
}

// 分页相关按钮事件
function bindPageEvents() {
  $('.list').on('click', function (e) {
    const target = $(e.target).closest('li[data-id]');
    if (target.length) {
      window.location.href = `./detail.html?id=${target.data('id')}`;
    }
  });

  $('.filter').on('click', function (e) {
    const target = $(e.target);
    target.siblings().removeClass('active');
    target.toggleClass('active');
    fetchList();
  });

  $('.search').on('keyup', function (e) {
    if (e.keyCode === 13) {
      currentPage = 1;
      $('.jump').val(currentPage);
      $('.first, .prev').addClass('disable');
      $('.next, .last').removeClass('disable');
      fetchList();
    }
  });

  $('.next').on('click', function (e) {
    if ($(e.target).hasClass('disable')) {
      return;
    }
    currentPage++;
    if (currentPage >= totalItems) {
      $('.next, .last').addClass('disable');
      currentPage = totalItems;
    } else {
      $('.prev, .last, .first').removeClass('disable');
    }
    $('.jump').val(currentPage);
    fetchList();
  });

  // 上一页
  $('.prev').on('click', function (e) {
    if ($(e.target).hasClass('disable')) {
      return;
    }
    currentPage--;
    if (currentPage <= 1) {
      $('.prev, .first').addClass('disable');
      currentPage = 1;
    } else {
      $('.next, .first, .last').removeClass('disable');
    }
    $('.jump').val(currentPage);
    fetchList();
  });

  $('.last').on('click', function (e) {
    if ($(e.target).hasClass('disable')) {
      return;
    }
    currentPage = totalItems;
    $('.first, .prev').removeClass('disable');
    $('.last, .next').addClass('disable');
    $('.jump').val(currentPage);
    fetchList();
  });

  $('.first').on('click', function (e) {
    if ($(e.target).hasClass('disable')) {
      return;
    }
    currentPage = 1;
    $('.first, .prev').addClass('disable');
    $('.last, .next').removeClass('disable');
    $('.jump').val(currentPage);
    fetchList();
  });

  $('.go').on('click', function () {
    currentPage = parseInt($('.jump').val());
    if (currentPage > totalItems) {
      currentPage = totalItems;
      $('.first, .prev').removeClass('disable');
      $('.last, .next').addClass('disable');
    } else if (currentPage < 1) {
      currentPage = 1;
      $('.first, .prev').addClass('disable');
      $('.last, .next').removeClass('disable');
    } else {
      $('.first, .prev').removeClass('disable');
      $('.last, .next').removeClass('disable');
    }
    $('.jump').val(currentPage);
    fetchList();
  });

  // 每页数量
  $('.pagesize').on('change', function (e) {
    pageSize = $(e.target).val();
    currentPage = 1;
    $('.first, .prev').addClass('disable');
    $('.last, .next').removeClass('disable');
    $('.jump').val(currentPage);
    fetchList();
  });
}
